/**
 * Created by lenovo on 2017/7/20.
 */
let DBPool = require('../dao/DBConnectPool');
let async = require('async');
let WXMember = require('./WXMemberController');

module.exports = {
    setCollection:function (req,res) {
        if (!req.signedCookies.userinfo ||!req.signedCookies.userinfo.openid) {
            res.json({errorMessage: '无法获取用户信息，请从公众号菜单重新进入！'});
            return;
        }
        let collectionType = req.body.type;
        let code = req.body.code;
        let openId = req.signedCookies.userinfo.openid;

        DBPool.getPoolConnection('mtsc', function (err, connection) {
            if (err) {
                res.json({errorMessage: '数据库链接错误'});
                connection.release();
                return;
            }
            async.waterfall(
                [
                    function (callback) {
                        let sql = 'SELECT * FROM member_user WHERE openid = ? ';
                        connection.query(sql, [openId], function (queryErr, rows) {
                            console.log('function-1');
                            if (queryErr) {
                                console.log(queryErr);
                                callback('获取用户信息失败！');
                            } else {
                                //console.log(queryErr);
                                if (rows.length == 0){
                                    callback('请注册会员！');
                                }else if (!rows[0].phone_number || rows[0].phone_number == 0){
                                    callback('请注册会员！');
                                }else {
                                    callback(null, {member_id:rows[0].member_id});
                                }
                            }
                        });
                    },
                    function (arg1,callback) {
                        let sql = '';
                        if (collectionType == 0){
                            sql = 'SELECT collection_id ' +
                                ' FROM member_movie_collection AS movie ' +
                                ' WHERE member_id = ? ' +
                                ' AND mid = ?';
                        } else if (collectionType == 1){
                            sql = 'SELECT collection_id ' +
                                ' FROM member_cinema_collection AS movie ' +
                                ' WHERE member_id = ? ' +
                                ' AND cinema_code = ?';
                        } else if (collectionType == 2){
                            sql = 'SELECT collection_id ' +
                                ' FROM member_album_collection AS movie ' +
                                ' WHERE member_id = ? ' +
                                ' AND album_id = ?';
                        } else {
                            callback('参数错误！');
                        }

                        connection.query(sql,[arg1.member_id,code] ,function (queryErr, rows) {
                            console.log('function-2');
                            if (queryErr) {
                                //console.log(queryErr);
                                callback('获取收藏信息失败！');
                            } else {
                                console.log(rows);
                                if (rows.length === 0){
                                    callback(null,arg1,0);
                                } else {
                                    callback(null,arg1,1);
                                }
                            }
                        })
                    },
                    function (arg1,arg2,callback) {

                        let date = new Date();
                        let Y = date.getFullYear() + '-';
                        let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
                        let D = date.getDate() + ' ';
                        let h = date.getHours() + ':';
                        let m = date.getMinutes() + ':';
                        let s = date.getSeconds();

                        let timestamp = Y+M+D+h+m+s;

                        let sql = '';
                        let array = [];
                        if (collectionType == 0){
                            if (arg2==0){
                                sql = 'INSERT INTO member_movie_collection (member_id, mid, createtime,updatetime) ' +
                                    ' VALUES ( ?, ?, ?, ?) ';
                                array.push(arg1.member_id);
                                array.push(code);
                                array.push(timestamp);
                                array.push(timestamp);
                            } else {
                                sql = 'DELETE FROM member_movie_collection ' +
                                    ' WHERE member_id = ? ' +
                                    ' AND mid = ? ';
                                array.push(arg1.member_id);
                                array.push(code);
                            }

                        } else if (collectionType == 1){
                            if (arg2==0){
                                sql = 'INSERT INTO member_cinema_collection (member_id, cinema_code, createtime,updatetime) ' +
                                    ' VALUES ( ?, ?, ?, ?) ';
                                array.push(arg1.member_id);
                                array.push(code);
                                array.push(timestamp);
                                array.push(timestamp);
                            } else {
                                sql = 'DELETE FROM member_cinema_collection ' +
                                    ' WHERE member_id = ? ' +
                                    ' AND cinema_code = ? ';
                                array.push(arg1.member_id);
                                array.push(code);
                            }
                        } else if (collectionType == 2){
                            if (arg2==0){
                                sql = 'INSERT INTO member_album_collection (member_id, album_id, createtime,updatetime) ' +
                                    ' VALUES ( ?, ?, ?, ?) ';
                                array.push(arg1.member_id);
                                array.push(code);
                                array.push(timestamp);
                                array.push(timestamp);
                            } else {
                                sql = 'DELETE FROM member_album_collection ' +
                                    ' WHERE member_id = ? ' +
                                    ' AND album_id = ? ';
                                array.push(arg1.member_id);
                                array.push(code);
                            }
                        } else {
                            callback('参数错误！');
                        }

                        connection.query(sql,array ,function (queryErr, result) {
                            console.log('function-3');
                            console.log(sql);
                            console.log(array);
                            if (queryErr) {
                                //console.log(queryErr);
                                callback('收藏失败！');
                            } else {
                                console.log(result);
                                callback(null,result);
                            }
                        })
                    },
                ], function (err, result) {
                    if (err) {
                        res.json({errorMessage:err});
                        connection.release();
                        return;
                    }
                    res.json(result);
                    connection.release();
                });
        });
    },
    showCollection:function (req, res) {
        let title = '收藏';
        WXMember.checkPhoneNumber(req,res,function (err, code, result) {
            if (code){
                if(code == 10001){
                    res.render('wx-activation', {
                        title: '手机号绑定',
                    });
                } else {
                    res.render('wx-404', {
                        title: title,
                        errorMessage: err
                    });
                }
            } else {
                res.render('wx-collection',{
                    title:title
                })
            }
        });
    },

    getCollection:function (req, res) {
        let collectionType = req.body.type;
        let pageCinema = req.body.pageCinema;
        let pageMovie = req.body.pageMovie;
        let pageAlbum = req.body.pageAlbum;
        let limit = 10;

        WXMember.checkPhoneNumber(req,res,function (err, code, result) {
            if (code){
                console.log('WXCollectionController.js:(1)'+ err)
                res.json({errorMessage: err});
            } else {
                let lat = req.body.lat;
                let lng = req.body.lng;
                console.log('WXCollectionController.js:(3)'+ result.member_id);
                let memberId = result.member_id;
                DBPool.getPoolConnection('mtsc', function (connectionErr, connection) {
                    if (connectionErr) {
                        console.log('WXCollectionController.js:(2)'+ connectionErr)
                        res.json({errorMessage: '数据库链接错误'});
                        connection.release();
                        return;
                    }
                    if (collectionType == 0){
                        let sql = 'SELECT m.*,DATE_FORMAT(m.publishdate,"%Y-%m-%d") as publish ' +
                            ' FROM member_movie_collection AS c ' +
                            ' INNER JOIN movie as m ON m.mid = c.mid ' +
                            ' WHERE c.member_id = ? ' +
                            ' ORDER BY c.updatetime DESC ' +
                            ' LIMIT ?,? ';
                        connection.query(sql,[memberId,pageMovie*limit,limit] ,function (queryErr, rows) {
                            if (queryErr) {
                                console.log('WXCollectionController.js:(4)'+ queryErr)
                                res.json({errorMessage: '获取收藏信息失败！'});
                            } else {
                                let flg = 0;
                                if (rows.length < limit) {
                                    flg = 1;
                                }
                                res.json({
                                    collection: rows,
                                    isLast:flg
                                });
                            }
                            connection.release();
                        })
                    } else if (collectionType == 1){
                        let sql = 'SELECT m.* ,b.name as region_name, ' +
                            ' (m.cinema_lat - ?) * (m.cinema_lat - ?) + (m.`cinema_long` - ?) * (m.`cinema_long` - ?) AS distance ' +
                            ' FROM member_cinema_collection AS c ' +
                            ' INNER JOIN cinema as m ON c.cinema_code = m.cinema_code ' +
                            ' INNER JOIN cinema_region AS b ON m.cinema_regionid = b.id' +
                            ' WHERE c.member_id = ? ' +
                            ' ORDER BY c.updatetime DESC ' +
                            ' LIMIT ?,? ';
                        connection.query(sql,[lat,lat,lng,lng,memberId,pageCinema*limit,limit] ,function (queryErr, rows) {
                            if (queryErr) {
                                console.log('WXCollectionController.js:(4)'+ queryErr)
                                res.json({errorMessage: '获取收藏信息失败！'});
                            } else {
                                let flg = 0;
                                if (rows.length < limit) {
                                    flg = 1;
                                }
                                res.json({
                                    collection: rows,
                                    isLast:flg
                                });
                            }
                            connection.release();
                        })
                    } else if (collectionType == 2){
                        let sql = 'SELECT m.* ' +
                            ' FROM member_album_collection AS c ' +
                            ' INNER JOIN movie_album as m ON c.album_id = m.album_id ' +
                            ' WHERE c.member_id = ? ' +
                            ' ORDER BY c.updatetime DESC ' +
                            ' LIMIT ?,? ';
                        connection.query(sql,[memberId,pageAlbum*limit,limit] ,function (queryErr, rows) {
                            if (queryErr) {
                                console.log('WXCollectionController.js:(4)'+ queryErr)
                                res.json({errorMessage: '获取收藏信息失败！'});
                            } else {
                                let flg = 0;
                                if (rows.length < limit) {
                                    flg = 1;
                                }
                                res.json({
                                    collection: rows,
                                    isLast:flg
                                });
                            }
                            connection.release();
                        })
                    } else {
                        res.json({errorMessage: '参数错误！'});
                        connection.release();
                    }
                });
            }
        });
    }
};
